/*
 * @lc app=leetcode.cn id=541 lang=swift
 *
 * [541] 反转字符串 II
 */

// @lc code=start
class Solution {
    func reverseStr(_ s: String, _ k: Int) -> String {
        var index = 0
        var result = ""
        while index + 2*k <= s.count {
            let leftKString = s[s.index(s.startIndex, offsetBy: index) ..< s.index(s.startIndex, offsetBy: index+k)]
            result.append(String(leftKString.reversed()))
            let rightKString = s[s.index(s.startIndex, offsetBy: index + k) ..< s.index(s.startIndex, offsetBy: index + 2*k)]
            result.append(String(rightKString))
            
            index += 2*k
        }
        
        if index + k > s.count {
            let leftKString = s[s.index(s.startIndex, offsetBy: index) ..< s.endIndex]
            result.append(String(leftKString.reversed()))
        }else{
            let leftKString = s[s.index(s.startIndex, offsetBy: index) ..< s.index(s.startIndex, offsetBy: index+k)]
            result.append(String(leftKString.reversed()))
            let rightKString = s[s.index(s.startIndex, offsetBy: index + k) ..< s.endIndex]
            result.append(String(rightKString))
        }
        return result
    }
}
// @lc code=end

